<template>
<section>
  <el-col :span="24" style="padding-top:10px;padding-bottom:10px;">
            <el-button round type="primary" @click="()=>{dialogFormVisible = true;optionType=1}"  size="small" icon="el-icon-plus">新增用户</el-button> 
             <!-- <el-dropdown trigger="click">
                <el-button round size="small" type="primary" plain class="el-dropdown-link">
                    <i><font-awesome-icon :icon="['far','edit']"/></i>&nbsp;批量操作
                </el-button>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>禁用</el-dropdown-item>
                    <el-dropdown-item>删除</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown> -->
        </el-col>
 
     <el-table
      v-loading="listLoading"
      border
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection">
      </el-table-column>
      <el-table-column
      fixed
        prop="userName"
        label="用户名" 
        width="120px"
        show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        label="真实姓名" 
        width="130px"
        prop="realName" >
      </el-table-column>
      <el-table-column
        label="状态" 
        width="80px" >
         <template slot-scope="scope">
              <el-tag v-show="scope.row.status==1" size="mini" type="success">正常</el-tag>
              <el-tag v-show="scope.row.status==5" size="mini"  type="info">已禁用</el-tag>
            </template>
      </el-table-column>
      <el-table-column
        label="昵称" 
        width="130px"
        prop="nickName" >
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色" >
        <template slot-scope="scope">
          {{scope.row.roleName.length==0?"未分配权限":scope.row.roleName}}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
            size="mini"
            v-if="user.id!=scope.row.id"
            @click="handleFore(scope.$index, scope.row)">{{scope.row.status==5?"解禁":"禁用"}}</el-button>
          <el-button
            v-if="user.id!=scope.row.id"
            key="delUser"
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
   <el-col :span="24" class="toolbar">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum">
        </el-pagination>
    </el-col>


        <el-dialog :title="optionType==1?'添加用户':'修改用户'" @close="resetForm('addUserForm')" :visible.sync="dialogFormVisible" width="500px">
            <el-row>
                <el-col :span="24">
                     <el-alert style="margin-bottom:10px;" 
                     title="请谨慎分配角色（权限）" 
                     close-text="知道了" type="warning"></el-alert>
                </el-col>
            </el-row>
            <el-form :model="addForm" :rules="rules" ref="addUserForm" size="small" label-width="80px"> 
                    <el-form-item label="用户名" prop="userName">
                        <el-input clearable v-model="addForm.userName"></el-input>
                    </el-form-item>  
                    <el-form-item label="密码" prop="pwd">
                        <el-input clearable v-model="addForm.pwd"></el-input>
                    </el-form-item> 
                    <el-form-item label="真实姓名" prop="realName">
                        <el-input clearable v-model="addForm.realName"></el-input>
                    </el-form-item> 
                    <el-form-item label="手机号" prop="mobile">
                        <el-input clearable v-model="addForm.mobile"></el-input>
                    </el-form-item>
                    <el-row>
                        <el-col :span="18">
                            <el-form-item label="角色" prop="selectRole">
                            <el-select
                                v-model="addForm.selectRole"
                                multiple
                                filterable 
                                @visible-change="visibleChange"
                                default-first-option
                                placeholder="请选择角色标签">
                                <el-option
                                v-for="item in roles"
                                :key="item.id"
                                :label="item.role"
                                :value="item.id">
                                </el-option>
                            </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-popover
                                placement="top-start"
                                title="提示"
                                width="220"
                                trigger="hover"
                                content="如果没有角色列表，请前往[系统设置]-[角色管理]菜单添加角色">
                                <i slot="reference" style="color:#E6A23C;font-size:18px;"><font-awesome-icon :icon="['fas','info-circle']"/></i>
                            </el-popover>
                        </el-col>
                    </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('addUserForm')" :loading="loading">确 定</el-button>
            </div>
        </el-dialog> 
</section>
   
</template>

<script>
import api from "@/service/api";
import http from "@/service/http";
//引用数据操作API
import store from '@/store'
//引用vuex的导入语法糖功能
import {createNamespacedHelpers} from 'vuex';
const {mapGetters,mapActions}=createNamespacedHelpers('system/user');

export default {
  data() {
    return {
      user:{},
      optionType:1,//更新2，添加1 
	    dialogFormVisible: false,
      loading: false,
      addForm: {
        userName: "",
        pwd: "",
        realName: "",
        mobile: "",
        roles: [],
        selectRole: []
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        pwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
        realName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" }
        ],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        selectRole: [
          { required: true, message: "请选择角色", trigger: "change" }
        ]
      },
      roles: []
    };
  },
  //计算属性
		computed:{
			//导入store的getters属性
			...mapGetters(['tableData','currentPage','listLoading','totalNum','pageSize'])
		},
  methods: {
    //导入actions方法
			...mapActions(['getUsers','handleSelectionChange','handleSizeChange','handleCurrentChange']),
			
    handleEdit(index, row) {
        this.optionType = 2;
        this.dialogFormVisible = true;
        this.addForm.userName = row.userName;
        this.addForm.realName = row.realName;
        this.addForm.mobile = row.mobile;
        this.addForm.selectRole = row.roleName;
    },
    handleFore(index, row){
      let infoStr = row.status == 5?"解禁":"禁用";
      this.$confirm('确认'+infoStr+'['+row.userName+']吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(() => {
          var param = [row.id]; 
           http.post(api.sysApi.batchDisabled, param).then(data => {
              if(!data.success){
              return;
            }
              this.$message({
                showClose: true,
                message: "已禁用",
                type: "success"
              });
              //更新列表
              this.getUsers(); 
            });
      }).catch(() => {});
    },
    handleDelete(index, row) { 
      this.$confirm('确认删除['+row.userName+']吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var param = [row.id]; 
                    this.delUser(param);
                }).catch(() => {});
    },
    resetForm(formName) { 
      this.addForm = {selectRole:[]}; 
      this.$refs[formName].resetFields();
    },
    submitForm(formName) { 
      this.$refs[formName].validate(valid => {
        if (valid) {
          var param = {
            username: this.addForm.userName,
            password: this.addForm.pwd,
            realName: this.addForm.realName,
            mobile: this.addForm.mobile,
            roleIds: this.addForm.selectRole
          };
          console.log(param);
          if(this.optionType==1){
            this.addUser(param);
          }else{
            this.updateUser(param);
          }
        } else {
          return false;
        }
      });
    },
    delUser(param) { 
      http.post(api.sysApi.batchDelete, param).then(data => {
        if(!data.success){
				return;
			}
        this.$message({
          showClose: true,
          message: "删除成功",
          type: "success"
        });
        //更新列表
        this.getUsers(); 
      });
    },
    addUser(param) {
      this.loading = true;
      http.post(api.sysApi.addUser, param).then(data => {
        if(!data.success){
				return;
			}
        this.$message({
          showClose: true,
          message: "添加成功",
          type: "success"
        });
        //更新列表
        this.getUsers();
        this.dialogFormVisible = false;
        this.loading = false;
      });
    },
    updateUser(param) {
      console.log('更新用户')
      // this.loading = true;
      // http.post(api.sysApi.addUser, param).then(data => {
      //   this.$message({
      //     showClose: true,
      //     message: "添加成功",
      //     type: "success"
      //   });
      //   //更新列表
      //   this.getUsers();
      //   this.dialogFormVisible = false;
      //   this.loading = false;
      // });
    },
    visibleChange(val) {
      if (!val) {
        //只有显示时才请求网络
        return;
      }
      //请求角色列表‘
      let param={
        pageNum:1,pageSize:200
      }
      http.post(api.sysApi.roleList, param).then(data => {
        this.roles = data.data;
      });
    }
  },
  mounted(){
      this.user = JSON.parse(localStorage.getItem('user'));
       this.getUsers()
  }
};
</script>

<style>
.el-pagination {
  float: right;
}

</style>
